﻿using Microsoft.AspNetCore.Http;

namespace CommunityToolKit.RefreshToken;

/// <summary>
/// 
/// </summary>
/// <param name="next"></param>
/// <param name="generateJwtToken"></param>
public class RefreshTokenMiddleware
{
    private readonly RequestDelegate _next;
    private readonly Func<string, string, string> _generateJwtToken;

    public RefreshTokenMiddleware(RequestDelegate next, Func<string, string, string> generateJwtToken)
    {
        _next = next;
        _generateJwtToken = generateJwtToken;
    }
    
    public async Task InvokeAsync(HttpContext context)
    {
        var accessToken = context.Request.Headers["Authorization"].ToString();
        var refreshToken = context.Request.Headers["RefreshToken"].ToString();
        accessToken = _generateJwtToken(accessToken, refreshToken ?? throw new InvalidOperationException());
        context.Response.Headers.Append("Authorization", accessToken);
        await _next(context);
    }
}